package com.veterinaria.dao;

import java.io.Reader;
import java.util.ArrayList;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.veterinaria.bean.EmpleadoBean;
import com.veterinaria.services.EmpleadoService;

public class EmpleadoDAO implements EmpleadoService{

	SqlSessionFactory sqlmapper= null;{
	   	 try {
				
			
	   	 Reader reader = Resources.getResourceAsReader("ConfiguracionIbatis.xml");
	   	 
	   	 sqlmapper =new  SqlSessionFactoryBuilder().build(reader);
	   	 } catch (Exception e) {
					e.printStackTrace();
				}
	    }
	
	@Override
	public ArrayList<EmpleadoBean> listarEmpleados(EmpleadoBean emp)
			throws Exception {
		ArrayList<EmpleadoBean> lista=new ArrayList<>();
		 SqlSession session = sqlmapper.openSession();		
			try {			
				lista= (ArrayList<EmpleadoBean>)session.selectList("empleadoxml.buscarEmpleado",emp);			
			} catch (Exception e) {
				e.printStackTrace();
			}finally{ session.close();}
			return lista;	
	}

	@Override
	public EmpleadoBean obtenerEmpledao(EmpleadoBean emp) throws Exception {
		EmpleadoBean empl=null;
		SqlSession session = sqlmapper.openSession();			
		try {				
			empl= (EmpleadoBean) session.selectOne("empleadoxml.obtenerEmpleado",emp);				
		} catch (Exception e) {
			e.printStackTrace();
		}finally{ session.close();}
		System.out.println("EMPLEADO DNI"+empl.getDni());
		return empl;
	}

	@Override
	public void eliminarEmpleado(EmpleadoBean emp) throws Exception {

		System.out.println("DNI EMPLEADO ELIMINADO::"+emp.getDni());
		SqlSession session = sqlmapper.openSession();
		String msg="";
		try {
			msg="exito"+ session.insert("empleadoxml.eliminarEmpleado",emp);
			session.commit();
		} catch (Exception e) {
			msg=e.getMessage();
			session.rollback();
		}finally{ session.close();}
		
	}

	@Override
	public void grabarEmpleado(EmpleadoBean emp) throws Exception {

		 SqlSession session = sqlmapper.openSession();
			String msg="";
			try {
				msg="exito"+ session.insert("empleadoxml.insertarEmpleado",emp);
				session.commit();
			} catch (Exception e) {
				e.printStackTrace();
				msg=e.getMessage();
				session.rollback();
			}finally{ session.close();}
			
	}

	@Override
	public void actualizarEmpleado(EmpleadoBean emp) throws Exception {

		SqlSession session = sqlmapper.openSession();
		String msg="";
		try {
			msg="exito"+ session.insert("empleadoxml.actualizarEmpleado",emp);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			msg=e.getMessage();
			session.rollback();
		}finally{ session.close();}
		System.out.println("ENTRO A ACTUALIZAR EMPLEADO");
		System.out.println("emp nombre ::"+emp.getNomEm());
		
	}

}
